#-*- codeing = utf-8 -*-
#@Time : 2020/10/30 13:25
#@Author : 阳某
#@File : 03.python绘制电商网站转化漏斗图.py
#@Software : PyCharm

'''

漏斗图：适用于业务流程环节多的流程分析，通过漏斗各环节业务数据的比较，能够直观地发现问题所在。

实例：数据来自kaggle网站的"E-commerce website Funnel analysis"
地址为：https://www.kaggle.com/aerodinamicc/ecommerce-website-funnel-analysis

网站很简单，有四个页面数据：

home_page_table.csv，首页用户访问数据
search_page_table.csv，搜索页用户访问数据
payment_page_table.csv，支付信息页用户访问数据
payment_confirmation_table.csv，支付成功页用户访问数据
user_table.csv，用户信息数据
目标：绘制转化漏斗，查看是否正常
'''

import pandas as pd

df_home_page = pd.read_csv("./datas/ecommerce-website-funnel-analysis/home_page_table.csv")
df_search_page = pd.read_csv("./datas/ecommerce-website-funnel-analysis/search_page_table.csv")
df_payment_page = pd.read_csv("./datas/ecommerce-website-funnel-analysis/payment_page_table.csv")
df_payment_confirmation_page = pd.read_csv("./datas/ecommerce-website-funnel-analysis/payment_confirmation_table.csv")
df_user_table = pd.read_csv("./datas/ecommerce-website-funnel-analysis/user_table.csv")


# 查看首页数据
print(df_home_page.head(3))
# 查看搜索页数据
print(df_search_page.head(3))
# 查看支付信息页数据
print(df_payment_page.head(3))
# 查看支付成功页数据
print(df_payment_confirmation_page.head(3))
# 查看用户信息表
print(df_user_table.head(3))
# 查看设备的类型
print(df_user_table['device'].value_counts())
# 查看性别类型
print(df_user_table['sex'].value_counts())


# 3.关联5个数据表为一个大表
df_merge = df_user_table

for df_inter in [df_home_page, df_search_page, df_payment_page, df_payment_confirmation_page]:
    # 每次循环都会往df_merge中添加新列
    df_merge = pd.merge(
        left=df_merge,
        right=df_inter,
        left_on="user_id",
        right_on="user_id",
        how="left"
    )

print(df_merge)
df_merge.columns = [
    "user_id", "date", "device", "sex",
    "home_page", "search_page", "payment_page", "confirmation_page"]
print(df_merge)
print(df_merge.shape)
# 3. 计算每个页面的用户数目
# 目的是给漏斗图填充数据，pyecharts需要的格式为：数据格式为[(key1, value1), (key2, value2)]
datas = []
for column in ["home_page", "search_page", "payment_page", "confirmation_page"]:
    user_count = df_merge[column].dropna().size
    datas.append((column, user_count))
print(datas)

# 方便查看对比，进行归一化
max_count = datas[0][1]
datas_norm = [
              (x, round(y*100/max_count, 2))
              for x,y in datas
             ]
print(datas_norm)

# 4. 绘制漏斗图
from pyecharts import options as opts
from pyecharts.charts import Funnel
funnel = Funnel()
funnel.add("用户比例", datas_norm)
funnel.render_notebook()
